using Items;
using Services;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class ItemUI : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler
{
    private ItemUI_Manager itemUI_manager;
    private Services.EventSystem eventSystem;
    private ContainerUI_Manager containerUI_manager;
    private ItemStack stack;

    private Text[] m_texts;
    private Image[] m_images;

    private void Awake()
    {
        itemUI_manager = CommonUI.GetUIComponent<ItemUI_Manager>();
        containerUI_manager = GetComponentInParent<ContainerUI_Manager>();
        m_texts = GetComponentsInChildren<Text>();
        m_images = GetComponentsInChildren<Image>();
        eventSystem = ServiceLocator.Get<Services.EventSystem>();
    }

    public void Initialize(ItemStack item, Sprite background)
    {
        stack = item;
        m_images[0].sprite = background;
        m_images[1].sprite = stack.ItemAttached.icon;
        m_texts[0].text = stack.ItemAttached.name;
        m_texts[1].text = $"{stack.Count}";
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        string information = stack.GetInformation();
        itemUI_manager.InvokeMouseEvent(stack, containerUI_manager.Container, EMouseEvent.Enter);
        eventSystem.Invoke<string, Vector2, float>(EEvent.View, information, transform.position, containerUI_manager.Panel.offset);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        itemUI_manager.InvokeMouseEvent(stack, containerUI_manager.Container, EMouseEvent.Exit);
        eventSystem.Invoke(EEvent.EndView);
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        EMouseEvent click = EMouseEvent.None;
        if (eventData.button == PointerEventData.InputButton.Left)
        {
            if (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt))
                click = EMouseEvent.AltLeft;
            else
                click = EMouseEvent.Left;
        }
        else if (eventData.button == PointerEventData.InputButton.Right)
        {
            if (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt))
                click = EMouseEvent.AltRight;
            else
                click = EMouseEvent.Right;
        }
        itemUI_manager.InvokeMouseEvent(stack, containerUI_manager.Container, click);
        eventSystem.Invoke(EEvent.EndView);
    }
}